import React, {createRef} from "react";
import FileIcon from "../../assets/center/FileIcons";
import {
    EditOutlined, CloudDownloadOutlined, ShareAltOutlined, DeleteOutlined, FileOutlined, SnippetsOutlined
} from "@ant-design/icons";
import { Card, Checkbox, Input, Menu, message, Modal} from "antd";
import '../../assets/center/FileCards.css'
import '../../assets/center/MiddleContent.css'
import {asyncContentDelete, asyncContentPut, asyncDownloadToken} from "../../api/middle/centerContent";

const MenuItem = Menu.Item;
export default class FileCard extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            FileInfo: props.FileInfo,
            hover: false,
            check: false,
            rename: false,
        };
        this.inputRef = createRef();

    }
    onHover = ()=>{
        this.setState({hover: true});
        this.props.handleMouseOnCards(true);
    }
    offHover= ()=>{
        this.setState({hover: false});
        this.props.handleMouseOnCards(false);
    }
    handleCardMouseUp = e => {
        if (e.button === 2) {
            e.stopPropagation();
            this.props.handleCardMenuCall(this.fileItems, e);
        }
    }
    onCheckChange = e=>{
        this.props.handleCheckChange(e.target.checked)
        this.setState({check: e.target.checked});
        // console.log(this.state.FileInfo.file_id);
    }
    //调用转化文本框
    onRename = ()=>{
        this.setState({rename: true});
    }
    //文本框输入回调
    onNameSubmit = this.props.asyncDisableCall(async e=>{
        try {
            this.setState({rename: false,});
            this.props.tellNameRepeat(e.target.value);
            await asyncContentPut({
                cookie: '',
                directory: this.state.FileInfo.path +'/'+ this.state.FileInfo.name,
                new_name: e.target.value
            });
            this.setState({
                FileInfo: {
                    ...this.state.FileInfo,
                    name: e.target.value,
                    type: this.fileType(e.target.value)
                }
            });
            message.success(`文件名修改成功：${e.target.value}`);

        } catch (e) {
            message.error(`文件名修改失败：${e}`);
        }

    })
    //收藏回调
    onStar = async e =>{
        try{
            await asyncContentPut({
                cookie: '',
                directory: this.state.FileInfo.path + '/' + this.state.FileInfo.name,
                is_starred: e.target.checked
            });
            this.setState({
                FileInfo: {
                    ...this.state.FileInfo,
                    is_starred: e.target.checked
                }
            });
        } catch (e) {
            message.error(`收藏失败：${e}`);
        }
    }
    //获取下载直链
    getDownloadURL = async (resolve, reject)=>{
        try {
            const [tokenMessage] = await asyncDownloadToken({
                cookie: '',
                file_id: this.state.FileInfo.file_id
            }).catch(e => {
                throw new Error(`获取${this.state.FileInfo.name}下载口令失败：${e}`);
            });
            if (resolve)
                resolve(['/v1/file/download?auth=' + tokenMessage.msg, this.state.FileInfo.name]);
            console.log(`获取${this.state.FileInfo.name}下载口令成功`);
            return '/v1/file/download?auth=' + tokenMessage.msg;
        } catch (e){
            if(reject)  reject(e);
            else    throw e;
        }
    }
    //文件下载
    onDownload = this.props.asyncDisableCall(async ()=>{
        try {
            const url = await this.getDownloadURL();
            // window.open(url);
            const a = document.createElement('a');
            a.href = url;
            a.download = this.state.FileInfo.name;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        } catch (e) {
            message.error(`下载失败：${e}`)
        }
    });
    //文件分享
    onShare = this.props.asyncDisableCall(async ()=>{
        try {
            const url = await this.getDownloadURL();
            Modal.success({
                title: '分享文件',
                content: (<span>链接：<a href={url} download={this.state.FileInfo.name}>{url}</a></span>)
            })
        }catch (e) {
            message.error(`分享失败：${e}`)
        }
    })
    //删除一个
    onDelete = async (resolve, reject)=>{
        const [Message] = await asyncContentDelete({
            cookie: '',
            directory: this.state.FileInfo.path +'/'+ this.state.FileInfo.name
        });
        if(Message.succeed) {

            if(resolve)
                resolve(Message);
            else
                message.success(`文件删除成功：${this.state.name}`);
        }else {
            if(reject)
                reject(Message);
            else
                message.error(`文件删除失败：${Message.msg}`);
        }
    }
    //删除函数
    onOneDelete = this.props.asyncRefreshCall(this.onDelete);
    stopPropagation = e => {
        e.stopPropagation();
    }
    onCopy = () => {
        navigator.clipboard.writeText(this.state.FileInfo.name)
            .then(()=>message.success('复制成功'))
            .catch(e=> message.error(`复制失败: ${e}`))
    }
    componentDidUpdate(prevProps) {
        if(prevProps.checkedSum !== this.props.checkedSum){
            if(this.props.checkedSum === this.props.fileSum)
                this.setState({check: true});
            else if(!this.props.checkedSum)
                this.setState({check: false});
        }
        if (prevProps.FileInfo !== this.props.FileInfo) {
            this.setState({FileInfo: this.props.FileInfo});
        }
        if(this.inputRef.current){
            this.inputRef.current.focus({
                cursor: 'all'
            });
        }
    }
    fileItems = (<>
        <MenuItem key={4} onClick={this.onRename} icon={<EditOutlined />}>重命名</MenuItem>
        <MenuItem key={5} onClick={this.onCopy} icon={<SnippetsOutlined />}>复制文件名</MenuItem>
        <MenuItem key={6} icon={<FileOutlined />} >复制文件</MenuItem>
        <MenuItem key={7} onClick={this.onDownload} icon={<CloudDownloadOutlined />}>下载文件</MenuItem>
        <MenuItem key={8} onClick={this.onShare} icon={<ShareAltOutlined />}>分享文件</MenuItem>
        <MenuItem key={9} onClick={this.onOneDelete} icon={<DeleteOutlined />} danger>删除文件</MenuItem>
    </>);
    render() {
        return (
            <Card
                className='Card'
                title={<>
                    {
                        this.state.rename || ((this.state.hover||!!this.props.checkedSum) &&
                        <Checkbox onClick={this.stopPropagation} onChange={this.onCheckChange} checked={this.state.check}/>)
                    }{
                        this.state.rename
                            ?
                            <Input
                                ref={this.inputRef}
                                size='small'
                                defaultValue={this.state.FileInfo.name}
                                onPressEnter={this.onNameSubmit}
                                onBlur={this.onNameSubmit}/>
                            :
                            <span title={this.state.FileInfo.name} className='title'>{this.state.FileInfo.name}</span>
                    }
                </>}
                size="small"
                hoverable={this.state.FileInfo.is_directory}
                onMouseEnter={this.onHover}
                onMouseLeave={this.offHover}
                onMouseUp={this.handleCardMouseUp}
                onClick={this.state.FileInfo.is_directory? ()=>this.props.onEnterFolder(this.state.FileInfo.name):undefined}
                bodyStyle={{
                    position: 'relative',
                    display: 'flex',
                    justifyContent: 'center'
                }}
            >
                <label className='star' onClick={this.stopPropagation}>
                    <input type='checkbox' className='checkbox-trigger' checked={this.state.FileInfo.is_starred} onChange={this.onStar}/>
                    <svg viewBox="0 0 76 72" xmlns="http://www.w3.org/2000/svg">
                        <path
                            d="M40.3776 4.4078L45.7255 20.8668C46.7295 23.9569 49.6092 26.0491 52.8584 26.0491H70.1644C72.5862 26.0491 73.5932 29.1482 71.6339 30.5717L57.633 40.7439C55.0044 42.6537 53.9044 46.039 54.9085 49.1292L60.2563 65.5881C61.0047 67.8914 58.3685 69.8067 56.4092 68.3832L42.4084 58.211C39.7797 56.3012 36.2203 56.3012 33.5916 58.211L19.5908 68.3832C17.6315 69.8067 14.9953 67.8914 15.7437 65.5881L21.0915 49.1292C22.0956 46.039 20.9956 42.6537 18.367 40.7439L4.36612 30.5717C2.40685 29.1482 3.41377 26.0491 5.83559 26.0491H23.1416C26.3908 26.0491 29.2705 23.9569 30.2745 20.8668L35.6224 4.40779C36.3707 2.10452 39.6293 2.10451 40.3776 4.4078Z"
                            className='star-border'/>
                        <path d="M36 30L27 45" className='star-shine'/>
                        <path d="M27 32L24 37" className='star-shine'/>
                    </svg>
                </label>
                <FileIcon isDirectory={this.state.FileInfo.is_directory} fileType={this.state.FileInfo.file_type}/>
            </Card>
        )
    }
}